package be.kuleuven.mume.paginas;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import be.kuleuven.mume.R;
import be.kuleuven.mume.arrayAdapters.VakSelectAdapter;
import be.kuleuven.mume.framework.Vak;
import be.kuleuven.mume.hulpklassen.DataFetcher;
import be.kuleuven.mume.hulpklassen.HttpHelper;
import be.kuleuven.mume.hulpklassen.JSONHandler;
import be.kuleuven.mume.hulpklassen.JSONParser.VakkenParser;
import be.kuleuven.mume.listProxys.LastCellLoadingProxy;

public class VakkenEditPagina extends Activity implements OnItemClickListener{
	private static final int SAVE = 0;
	private static final int CANCEL = 1;
	
	private ArrayList<Vak> vakken;
	private VakSelectAdapter adapter;
	private DataFetcher<Vak> datafetcher;
	private LastCellLoadingProxy loadingProxy;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vakken_tabel);

		vakken = new ArrayList<Vak>();
		adapter = new VakSelectAdapter(this, vakken);
		loadingProxy = new LastCellLoadingProxy(adapter);

		ListView table = (ListView)findViewById(R.id.vakken);
		table.setAdapter(loadingProxy);
		adapter.notifyDataSetChanged();

		VakkenParser parser = new VakkenParser();
		datafetcher = new DataFetcher<Vak>(parser, Vak.VAK_URL, table, vakken, this.getBaseContext()){
			public void DataReceived(){
				if(!datafetcher.hasMoreData()){
					loadingProxy.setIsLoading(false);
				}
				adapter.notifyDataSetChanged();
			}
		};

		table.setTextFilterEnabled(true);
		table.setOnItemClickListener(this);
		table.setDescendantFocusability(ListView.FOCUS_BLOCK_DESCENDANTS);
	}
	
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		adapter.setChecked(arg2);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, SAVE, 0, R.string.save);
		menu.add(0, CANCEL, 1, R.string.cancel);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case SAVE:
			addVakken();
			finish();
			break;
		case CANCEL:
			finish();
		default:
			break;
		}
		return true;
	}

	private void addVakken() {
		JSONHandler h = new JSONHandler() {
			
			@Override
			public void handelJSON(JSONObject obj) {
				if(obj.has("error"))
					Toast.makeText(VakkenEditPagina.this, R.string.serverError, 10).show();
			}
		};
		
		for (Vak a : adapter.getChechedItems()) {
			HttpHelper.doGetInThread(Vak.getAddVakUrl(a.getVakId()), this, h);
		}
	}
	
	
}
